package com.itheima.web.servlet;

import cn.hutool.core.util.IdUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.domain.ResultInfo;
import com.itheima.domain.User;
import com.itheima.factory.BeanFactory;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.RandomStringUtils;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/UserServlet")
@MultipartConfig
public class UserServlet extends HttpServlet {
@Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求action
        String action=request.getParameter("action");

        //判断
        if ("register".equals(action)){
            this.register(request,response);
        }else if ("findByUsername".equals(action)){
            this.findByUsername(request,response);
        }else if ("sendSms".equals(action)){
            try {
                this.sendSms(request,response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if ("pwdLogin".equals(action)){
            this.pwdLogin(request,response);
        }else if ("logout".equals(action)){
            this.logout(request,response);
        } else if ("telLogin".equals(action)) {
            this.telLogin(request,response);
        }else if ("userInfo".equals(action)){
            this.userInfo(request,response);
        }else if ("updateInfo".equals(action)){
            this.updateInfo(request,response);
        }
    }



    //作为模板使用
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
    //UserService userService=new UserServiceImpl();
UserService userService= (UserService) BeanFactory.getBean("userService");

    // 个人信息修改
    protected void updateInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            // 1.接收请求参数map
            Map<String, String[]> parameterMap = request.getParameterMap();
            // 2.封装user实体
            User param = new User();
            BeanUtils.populate(param, parameterMap);
            //---------文件上传
            // a.获取文件对象
            Part part = request.getPart("pic");
            // b.获取文件名
            String fileName = part.getSubmittedFileName();
            // c.判断用户是否提交文件
            if (fileName.length() > 0) {
                // d.指定文件路径
                String path = "/pic/" + IdUtil.simpleUUID() + fileName;
                // e.获取服务器真实路径
                String realPath = request.getServletContext().getRealPath(path);
                // f.保存文件
                part.write(realPath);
                // g.给user设置图片访问地址
                param.setPic(path);

            }




            //-------上传结束
            // 3.调用service更新
            userService.updateInfo(param);
            // 4.根据uid查询service，重置到session中
            User currentUser = userService.findByUid(param.getUid());
            request.getSession().setAttribute("currentUser", currentUser);
            //5.重定向到 用户中心回显
            response.sendRedirect(request.getContextPath()+"/UserServlet?action=userInfo");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
//用户中心回显
    protected void userInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   //校验session
        Object currentUser = request.getSession().getAttribute("currentUser");
        if (currentUser==null){
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }
        //转发到home_index.jsp
        request.getRequestDispatcher("/home_index.jsp").forward(request,response);
    }

    protected void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //1.清楚session
        request.getSession().invalidate();
        // 2.重定向首页
        response.sendRedirect(request.getContextPath()+"/index.jsp");
    }
    protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //==验证码
        //1.获取请求参数
        String telephone=request.getParameter("telephone");
        String smsCode=request.getParameter("smsCode");
        //2.获取session中的验证码
        //String sessionCode=(String) request.getSession().getAttribute("smsCode_"+telephone);
        //a.升级为从jedis中获取
        Jedis jedis=new Jedis();
        String sessionCode = jedis.get("smsCode_" + telephone);

        //3.校验
        if (sessionCode==null||(!sessionCode.equals(smsCode))){
            //验证码不对
            request.setAttribute("resultInfo",new ResultInfo(false,"验证码不对"));

          request.getRequestDispatcher("/register.jsp").forward(request, response);
            return;
        }


        //1.获取请求参数
        Map<String,String[]>parameterMap=request.getParameterMap();
        //2.封装User实体
        User param=new User();

        try {
            BeanUtils.populate(param,parameterMap);
        } catch (Exception e) {
            throw new RuntimeException("实体封装失败...");
        }
        //3.调用service 实现注册
        ResultInfo resultInfo=userService.register(param);
           //4.判断
        if (resultInfo.getSuccess()){
          response.sendRedirect(request.getContextPath()+"/register_ok.jsp");
          //清楚session中的验证码
           // request.getSession().removeAttribute("smsCode_"+telephone);
            //升级为  清楚jedis
            jedis.del("smsCode_"+telephone);
        }else {
            request.setAttribute("resultInfo",resultInfo);
            request.getRequestDispatcher("/register.jsp").forward(request,response);
        }


    }
    protected void findByUsername(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1.接受请求参数
        String username=request.getParameter("username");
        //2.调用service查询
        User user=userService.findByUsername(username);
        ResultInfo resultInfo=null;
        //3.判断
        if (user!=null){
            resultInfo=new ResultInfo(false,"用户名已存在");
        }else {
            resultInfo=new ResultInfo(true,"可以注册");
        }
              //4.将resultInfo转为json
        ObjectMapper objectMapper=new ObjectMapper();
        String json=objectMapper.writeValueAsString(resultInfo);
        //5.通过response响应
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
    }
    protected void findByTelephone(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//1.接受请求
        String telephone=request.getParameter("telephone");
        // 2.调用service查询
          User user=userService.findByTelephone(telephone);
        ResultInfo resultInfo=null;
        // 3.判断
          if (user!=null){
              resultInfo=new ResultInfo(false,"手机号可以注册");
          }else {
              resultInfo=new ResultInfo(true,"手机号已被注册");
          }

        // 4.将resultInfo转为json
             ObjectMapper objectMapper=new ObjectMapper();
          String json=objectMapper.writeValueAsString(resultInfo);
        // 5.通过response响应
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);

    }
    //ajax发送短信
    private void sendSms(HttpServletRequest request, HttpServletResponse response) throws Exception {
    //1.获取请求参数
        String telephone=request.getParameter("telephone");
        //2.生成6位随机数
        String smsCode= RandomStringUtils.randomNumeric(6);
        //3.调用service完成短信发送，返回resultInfo
      ResultInfo resultInfo=  userService.sendSms(telephone,smsCode);
        // 4.如果发送成功，将验证码写入到session中
        if (resultInfo.getSuccess()){
            //request.getSession().setAttribute("smsCode_"+telephone,smsCode);
            //a.获取jedis链接
            Jedis jedis=new Jedis();
            //b.将验证码设置到jedis中  设置存活五分钟
            jedis.setex("smsCode_"+telephone,300,smsCode);
            //c.释放资源
            jedis.close();

            System.out.println("短信验证码："+smsCode);
        }
        // 5.将resultInfo转为json
        String json=new ObjectMapper().writeValueAsString(resultInfo);
        //6.response响应
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
    }
    protected void pwdLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //1.接受请求参数map
            Map<String, String[]> parameterMap = request.getParameterMap();
            //2.封装到User实体
            User param=new User();
            BeanUtils.populate(param,parameterMap);
            // 3.调用service登录，返回resultInfo
            ResultInfo resultInfo=userService.pwdLogin(param);
            //4.判断登录是否成功
            if (resultInfo.getSuccess()) {
                // resultInfo.getData() 获取service返回的user对象
                request.getSession().setAttribute("currentUser",resultInfo.getData());
            }
            //5.将resultInfo转为json响应到客户端
            String json =new ObjectMapper().writeValueAsString(resultInfo);
            //6.response响应
            response.setContentType("applicaton/json;charset=utf-8");
            response.getWriter().write(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    protected void telLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      //1.接受请求参数telephone
        String telephone = request.getParameter("telephone");
        //2.调用service查询
        User currentUser = userService.findByTelephone("telephone");
        ResultInfo resultInfo=null;
        // 3.校验手机号...
        if (currentUser==null){
            resultInfo=new ResultInfo(false,"手机号未注册");
        }else {
            // 4.校验验证码
            // 4.1 获取用户输入验证码
            String smsCode = request.getParameter("smsCode");
            // 4.2 将验证码写入获取session中
          // String sessionCode = (String) request.getSession().getAttribute("smsCode_" + telephone);
            //升级为jedis中获取
            Jedis jedis=new Jedis();
            String sessionCode = jedis.get("smsCode_" + telephone);
            // 4.3 校验
            if (sessionCode==null||(!sessionCode.equals(smsCode))){
                resultInfo=new ResultInfo(false,"验证码错误");
            }else {
                request.getSession().setAttribute("currentUser",currentUser);
                resultInfo=new ResultInfo(true,"登录成功");
                // 清除session中验证码
               // request.getSession().removeAttribute("smsCode_"+telephone);
                jedis.del("smsCode_"+telephone);
            }
            //释放资源
            jedis.close();
        }

        //5. 将resultInfo转为json，响应到客户端
String json=new ObjectMapper().writeValueAsString(resultInfo);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
    }
}